package com.xiang.api.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xiang.api.Util;
import com.xiang.api.entity.Message;
import com.xiang.api.entity.UrlId;
import com.xiang.sql.entity.User;
import com.xiang.sql.service.UploadService;
import com.xiang.sql.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Upload {
  private String suffix(Part part) {
    String ret = part.getSubmittedFileName();
    try {
      ret = ret.substring(ret.lastIndexOf('.'));
    } catch (Exception e) {
      if (ret.toLowerCase().equals("text/plain")) {
        ret = ".txt";
      } else {
        ret = ret.replaceAll("(?i).*\\/(.*)", ".$1");
        ret.replaceAll("/(?i)\\.jpeg$", ".jpg");
      }
    }
    return ret;
  }

  private String saveImg(Part file, boolean compress) throws IOException {
    String ret = Util.writeImg(file.getInputStream(), "public/upload/img/" + Util.sGetId32(), compress ? 1024 : null);
    if (ret == null) {
      ret = Util.formatFilename(String.format("public/upload/file/%s%s", Util.sGetId32(), suffix(file)), true);
      file.write(ret);
    }
    return ret.replace("\\", "/").replaceAll(".*/public(/upload/.*)", "$1");
  }

  private void run(String cmd) throws Exception {
    String[] cmds = { cmd };
    Process p = Runtime.getRuntime().exec(cmds);
    InputStream stderr = p.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;

    StringBuffer sb = new StringBuffer();
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }
  }

  public UrlId saveMedia(Part file, boolean pub) throws Exception {
    String id = String.valueOf(IdWorker.getId());
    String ret = (pub ? "public/upload/media/" : "crypto/") + id, s = file.getContentType(), p;
    String[] pa = { "fileItem", "tempFile", "path" };
    Object path = Util.getPrivate(file, pa);
    if (path == null) {
      throw null;
    }
    if (s.equals("video/mp4")) {
      ret += "/index.m3u8";
      p = Util.formatFilename(ret, true);
      run("ffmpeg -y -i " + (String) path + " -hls_time 5 -hls_list_size 0 -f hls " + p);
      s = new String(Util.readFile(p));
      int i = s.indexOf("#EXTINF");
      s = s.substring(0, i) + "#EXT-X-KEY:METHOD=AES-128,URI=\"/encrypt.key\",IV=0x00000000000000000000000000000000\n"
          + s.substring(i);
      Util.writeFile(p, s.getBytes());
    } else if (s.substring(0, 5).equals("audio")) {
      ret += ".aac";
      p = Util.formatFilename(ret);
      run("ffmpeg -y -i " + (String) path + " -c:a aac " + p);
    } else {
      throw null;
    }

    return new UrlId(id, ret.substring(6));
  }

  @Autowired
  UserService userService;

  @Autowired
  UploadService uploadService;

  @SuppressWarnings("null")
  public Object index(HttpServletRequest request) {
    try {
      User user = userService.getByToken(request.getHeader("token"));
      if (user != null /* && (user.per("文件上传") || user.per("上传文件创建")) */) {
        Part file = request.getPart("pic");
        if (file == null) {
          file = request.getPart("file");
        }
        String name = request.getParameter("public");
        boolean pub = name != null;
        if (pub && (name.equals("0") || name.equals("false"))) {
          pub = false;
        }
        name = request.getParameter("name");
        if (name == null && file != null) {
          name = file.getSubmittedFileName();
        }
        if (file == null || name == null) {
          throw new Exception("数据格式错误");
        }
        String compress = request.getParameter("compress"),
            f = saveImg(file, Boolean.parseBoolean(compress) || compress == null);

        com.xiang.sql.entity.Upload u = uploadService.create(user.id, request.getParameter("type"), name, f,
            request.getParameter("other"));
        return new UrlId(u);
      }
      return new Message("没有权限", true);
    } catch (Exception e) {
      System.out.println("上传错误: " + Util.errString(e));
      return new Message(Util.errString(e), true);
    }
  }
}
